package io.boot.common.aspect;

import io.boot.common.annotation.DataScope;
import io.boot.common.utils.BaseEntity;
import io.boot.modules.sys.controller.AbstractController;
import io.boot.modules.sys.entity.SysDeptEntity;
import io.boot.modules.sys.entity.SysRoleEntity;
import io.boot.modules.sys.entity.SysUserEntity;
import io.boot.modules.sys.service.*;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 数据过滤处理
 *
 * @author kyson
 */
@Aspect
@Component
public class DataScopeAspect extends AbstractController {

    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleDeptService sysRoleDeptService;
    @Autowired
    private SysDeptService sysDeptService;

    /**
     * 全部数据权限
     */
    public static final String DATA_SCOPE_ALL = "1";

    /**
     * 自定数据权限
     */
    public static final String DATA_SCOPE_CUSTOM = "2";

    /**
     * 部门数据权限
     */
    public static final String DATA_SCOPE_DEPT = "3";

    /**
     * 部门及以下数据权限
     */
    public static final String DATA_SCOPE_DEPT_AND_CHILD = "4";

    /**
     * 仅本人数据权限
     */
    public static final String DATA_SCOPE_SELF = "5";

    // 配置织入点
    @Pointcut("@annotation(io.boot.common.annotation.DataScope)")
    public void dataScopePointCut()
    {
    }

    @Before("dataScopePointCut()")
    public void doBefore(JoinPoint point) throws Throwable
    {
        handleDataScope(point);
    }

    protected void handleDataScope(final JoinPoint joinPoint)
    {
        // 获得注解
        DataScope controllerDataScope = getAnnotationLog(joinPoint);
        if (controllerDataScope == null)
        {
            return;
        }
        // 获取当前的用户
        SysUserEntity currentUser = getUser();
        if (currentUser != null)
        {
            // 如果是超级管理员，则不过滤数据
           dataScopeFilter(joinPoint, currentUser);
        }
    }



    /**
     * 数据范围过滤
     *
     * @param joinPoint 切点
     */
    public void dataScopeFilter(JoinPoint joinPoint, SysUserEntity user) {
        List<Long> roleList = sysUserRoleService.queryRoleIdList(user.getUserId());
        List<Long> userIdList = new ArrayList<>();
        for (Long roleId : roleList) {
            SysRoleEntity sysRoleEntity=sysRoleService.getById(roleId);
            if(sysRoleEntity.getDataScope().equals(DATA_SCOPE_CUSTOM)){
                /**
                 * 自定义数据权限
                 * 1.根据roleid 获取 部门dept 然后获取 createBy
                 */
                List<Long> deptList=sysRoleDeptService.byRoleGetDeptList(roleId);
                for (Long deptId:deptList){
                    SysDeptEntity sysDeptEntity=sysDeptService.getById(deptId);
                    List<Long> userIdLists=sysUserService.byDeptGetUserList(sysDeptEntity.getDeptId());
                    for (Long userIds:userIdLists) {
                        if(!userIdList.contains(userIds)){
                            userIdList.add(userIds);
                        }
                    }
                }
            }else if(sysRoleEntity.getDataScope().equals(DATA_SCOPE_DEPT)){
                /**
                 * 部门数据权限
                 * 1.根据当前用户 dept 获取 部门下的用户
                 */
                List<Long> userIdLists=sysUserService.byDeptGetUserList(user.getDeptId());
                for (Long userIds:userIdLists) {
                    if(!userIdList.contains(userIds)){
                        userIdList.add(userIds);
                    }
                }
            }else if(sysRoleEntity.getDataScope().equals(DATA_SCOPE_DEPT_AND_CHILD)){
                /**
                 * 部门及以下数据权限
                 * 1.根据roleid 获取 部门dept,以及自己的下级dept  然后获取 createBy
                 */
                SysDeptEntity sysDeptEntity=sysDeptService.getById(user.getDeptId());
                List<Long> userIdLists=sysUserService.byAncestorsAndDeptId(sysDeptEntity.getDeptId());
                for (Long userIds:userIdLists) {
                    if(!userIdList.contains(userIds)){
                        userIdList.add(userIds);
                    }
                }
            }else if(sysRoleEntity.getDataScope().equals(DATA_SCOPE_SELF)){
                /**
                 * 仅本人数据权限
                 * 1.createBy
                 */
                if(!userIdList.contains(user.getUserId())) {
                    userIdList.add(user.getUserId());
                }
            }
        }
        if (userIdList.size() > 0) {
            Map<String, Object> params = (Map<String, Object>) joinPoint.getArgs()[0];
            params.put("list",userIdList);
        }
    }

    /**
     * 是否存在注解，如果存在就获取
     */
    private DataScope getAnnotationLog(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (method != null)
        {
            return method.getAnnotation(DataScope.class);
        }
        return null;
    }
}
